
import md5 from 'js-md5';
import service from './api.js';
import { timeDown, formatDate, changeParams, formatHour, addClass, removeClass } from './utils';
import './style.css';

export default class HCISystem {
    constructor(options) {
        console.log('hciSystem---');
        const w = window.innerWidth;
        this.isMobile = w <= 450;
        this.initStatus = true;
        this.account_id = options.account_id;
        this.timer = null;
        this.initSuntory()
    }
    initSuntory() {
        this.getAjaxData();
    }
    async getAjaxData() {
        let res;
        try {
        res = await this.ajaxPost();
        } catch (err) {
        console.log(err);
        }
        if (res.code == 200) {
        let beginTime = res.data.begin_time || 0;
        let endTime = res.data.end_time || 0;
        let differTime = res.data.remain_time;
        let curTime = res.data.cur_time;
        let frequency = res.data.frequency;
        const configList = res.data.config_list;
        const list = configList.find(option => option.remain_time == differTime);
        const dataList = {
            beginTime,
            endTime,
            differTime,
            curTime,
        };
        if (!list) {
            setTimeout(() => {
            this.getAjaxData();
            }, frequency * 1000);
        }
        const openTime = `${formatDate(beginTime)} - ${formatDate(endTime)}`;
        this.getStopEle(openTime);
        this.getToastEle();
        !res.data.remain_time && this.openPopPage();
        res.data.remain_time && this.getToastMsgAction(dataList, list);
        }
    }

    getStopEle(openTime) {
        const pop = document.createElement('div');
        pop.classList = 'stop-study-page-fixed';
        let str = '';
        const w = window.innerWidth;
        const html = `
          <div class="hci-moon">
            <img src="//cdn.test.classba.cn/public/stopSystem/img/moon.png" />
          </div>
          <div class="hci-content">
            <div class="hci-head">非学习时段，系统停止开放</div>
            <div class="hci-body">
              <p>亲爱的同学，</p>
              <p>夜深人静，已经很晚啦！</p>
              <p>劳逸结合很重要哦！请在学习时段内来吧~</p>
              <div class="active-time">系统开放学习时段：${openTime}</div>
            </div>
          </div>
        `;
        str = !this.isMobile ? `<div class="stop-study-frame">${html}</div>` : html;
        pop.innerHTML = str;
    
        document.body.appendChild(pop);
    }
    getToastEle() {
        const w = window.innerWidth;
        const toast = document.createElement('div');
        toast.className = 'hci-stop-toast-fixed';
        let ele = '';
        ele = `
        <span class="hci-close-btn" id="hCloseBtn">x</span>
        <div class="hci-stop-toast-body" id="toastBody"></div>
        `;
        toast.innerHTML = ele;
        document.body.appendChild(toast);
    }
    getToastMsgAction(data, list) {
        let ele = '';
        const w = window.innerWidth;
        let countdown = list;
        let { beginTime, endTime, curTime, differTime } = data;
        const openTime = `${formatDate(beginTime)} - ${formatDate(endTime)}`;
        let allow_close = 1;
        let diffTime = endTime - curTime;
        console.log(differTime, 'differTime')
        if (w >= 1024) {
          if (!countdown && differTime) {
            ele = `
            <p>亲爱的同学，系统开放学习时段：${openTime}，</p>
            <p>非学习时段系统将强制下线请合理安排时间哦~</p>
            <p><span class="bold" id="hcountTime">10s</span>后自动关闭弹窗</p>
            `;
          } else if (countdown && differTime) {
            let { remain_time } = countdown;
            allow_close = countdown.allow_close;
            remain_time = parseInt(remain_time / 60);
            this.initStatus = true;
            ele = `
              ${!allow_close ? `<p>系统关闭倒计时：<span class="bold" id="hTimeDown">${timeDown(diffTime)}</span></p>` : ``}
              <p>亲爱的同学，系统将于${!allow_close ? formatHour(endTime) : `${remain_time}分钟后`}关闭！劳逸结合很重要哦！请在学习时段内来吧~</p>
              <p>系统开放学习时段：${openTime}</p>
              ${!allow_close ? `<p><span class="bold" id="hcountTime">10s</span>后自动关闭弹窗</p>` : ``}
            `;
          }
        } else if (w < 1024) {
          if (!countdown && differTime) {
            ele = `
            <p>亲爱的同学，系统开放学习时段：${openTime}，</p>
            <p>非学习时段系统将强制下线请合理安排时间哦~</p>
            <p><span class="bold" id="hcountTime">10s</span>后自动关闭弹窗</p>
            `;
          } else if (countdown && differTime) {
            let { remain_time } = countdown;
            allow_close = countdown.allow_close;
            remain_time = parseInt(remain_time / 60);
            this.initStatus = true;
            ele = `
              ${!allow_close ? `<p>系统关闭倒计时：<span class="bold" id="hTimeDown">${timeDown(diffTime)}</span></p>` : ''}
              ${allow_close ? `<p>亲爱的同学，系统将于${remain_time}分钟关闭！</p>` : ''}
              <p>劳逸结合很重要哦！请在学习时段内来吧~</p>
              <p>系统开放学习时段：${openTime}</p>
              ${allow_close ? '<p><span class="bold" id="hcountTime">10s</span>后自动关闭弹窗</p>' : ''}
            `;
          }
          
        }
        const toastEle = document.getElementById('toastBody');
        const toastCosEle = document.querySelector('.hci-stop-toast-fixed')
        toastEle.innerHTML = ele;
        if (this.initStatus && !countdown && differTime) {
          toastCosEle.style.display = 'block';
          addClass(toastCosEle, 'animate');
          setTimeout(() => {
            removeClass(toastCosEle, 'animate');
          }, 400);
          this.timeAction(allow_close, countdown, diffTime);
          this.initStatus = false;
        }
    }
    ajaxPost() {
        const data1 = {
          account_id: this.account_id,
          secret_key: 'RrA3N3Qytd7mV8nQ6kxIWo2NSRMf5TSF'
        };
        let param = changeParams(data1);
        param = md5(param);
        const newObj = Object.assign(data1, {sign: param});
        const data = {
          data: newObj
        }
        return service.request({
          baseURL: '//m.test.songshuai.com/api/userSupervision/checkLimitLearn',
          method: 'post',
          data,
        });
    }
    closeToastAction() {
        const toastCosEle = document.querySelector('.hci-stop-toast-fixed');
        this.timer && clearInterval(this.timer);
        this.timer = null;
        toastCosEle.style.display = 'none';
    }
    timeAction(allow_close, countdown, diffTime) {
        let curTime = 10;
        const toastCosEle = document.querySelector('.hci-stop-toast-fixed');
        const timeEle = document.getElementById('hcountTime');
        const timedownEle = document.getElementById('hTimeDown');
        const that = this;
        if (allow_close && !countdown) {
          const closeBtn = document.querySelector('.hci-close-btn');
          if (closeBtn) {
            closeBtn.style.display = 'block';
            closeBtn.addEventListener('click', function() {
              that.closeToastAction();
            });
          }
          this.timer = setInterval(() => {
            curTime --;
            curTime == 0 && this.closeToastAction();
            if (timeEle) timeEle.innerText = `${curTime}s`;
          }, 1000);
        }
        if (!allow_close) {
          diffTime = parseInt(diffTime);
          let timeDer = setInterval(() => {
            timedownEle.innerHTML = timeDown(diffTime);
            diffTime --;
            if (diffTime <= 0) {
              clearInterval(timeDer);
              diffTime = 0;
              this.closeToastAction();
              this.openPopPage();
            }
            
          }, 1000);
        }
    }
    openPopPage() {
        const popEle = document.querySelector('.stop-study-page-fixed');
        popEle.style.display = 'block';
    }
}